// mircoApp/new_coupon/new_coupon_detail/new_coupon_detail.js
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");

const app = getApp();
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    datainfo: {},
    info_arr: null,
    active: "",
    store_list: [],
    storeCoupon: {
      page: 1,
      total_page: 0,
      total: 0
    },
    // 转赠开关
    showPresenter: false,
    recharge_search: "",
    nickname: "",
    transferRadio: "1",
    couponNum: 1,
    // 核销
    verification: false,
    verificationImg: "",
    name: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.name) {
      this.setData({
        name: options.name
      })
    }
    if (options.id) {
      this.setData({
        id: options.id
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  toStore(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageC/o2o/o2oStore/o2oStore?store_id=' + id,
    })
  },
  combination_to(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/mircoApp/new_coupon/new_CouponCombination/new_CouponCombination?id=' + id,
    })
  },
  onclose() {
    this.setData({
      showPresenter: false
    })
  },
  async cancelRecharge(e) {
    let json = {
      id: this.data.id,
      transfer_type: this.data.transferRadio,
      num: this.data.couponNum
    };
    if (this.data.transferRadio == 1) {
      if (app._isTextEmpty(this.recharge_search)) {
        app.tips('请输入会员ID')
        return;
      }
      json.member_id = this.data.recharge_search;
    }
    if (this.data.transferRadio == 2) {
      if (app._isTextEmpty(this.recharge_search)) {
        app.tips("请输入转赠手机号");
        return;
      }
      json.mobile = this.data.recharge_search;
    }
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.new-coupon.frontend.controllers.member-coupon.transfer-coupon"),
      data: json
    })
    if (data.result) {
      this.setData({
        showPresenter: false,
      })
      if (this.data.transferRadio == 3) {
        wx.navigateTo({
          url: '/packageI/CouponShareShow/CouponShareShow?mark_id=' + data.data.mark_id,
        })
      }
    } else {
      app.tips(data.msg)
    }
  },
  async getmemberInfo() {
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("member.member.memberInfo"),
      data: {
        uid: this.data.recharge_search
      }
    })
    if (data.result) {
      this.setData({
        memberInfo: data.data ? data.data.nickname : '查无此用户'
      });
    } else {
      this.setData({
        memberInfo: '查无此用户'
      });
    }
  },
  changeRechargeNum(e) {
    console.log(e.detail)
    if (e.detail >= this.data.info_arr.coupon_num) {
      app.tips(`分享张数不足,当前可转赠数量为${this.data.info_arr.coupon_num}张`)
      this.setData({
        couponNum: e.detail
      })
      return
    }
    this.setData({
      couponNum: e.detail
    })
  },
  transferChange(e) {
    this.setData({
      recharge_search: "",
      nickname: '',
      transferRadio: e.detail
    })
  },
  close_verification() {
    this.setData({
      verification: false
    })
  },
  async clickWriteOff() {
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.new-coupon.frontend.controllers.member-coupon.write-off-code"),
      data: {
        id: this.data.id
      }
    })
    if (data.result) {
      this.setData({
        verificationImg: data.data.qr_code,
        verification: true
      })
    } else {
      app.tips(data.msg);
    }
  },
  showPresenter_Tap() {
    this.setData({
      showPresenter: true,
      transferRadio: "1"
    })
  },
  async getData() {
    let urlstr = app.getNetAddresss("plugin.new-coupon.frontend.controllers.member-coupon.get-detail");
    if (this.data.name == "new_coupon_detail_combination") {
      urlstr = app.getNetAddresss("plugin.new-coupon.frontend.controllers.coupon.detail");
    }
    let {
      data
    } = await app._postNetWork({
      url: urlstr,
      data: {
        id: this.data.id
      }
    })
    if (data.result) {
      console.log(data)
      this.setData({
        datainfo: data.data,
        info_arr: data.data.info,
      })
      console.log(this.data.datainfo.avatar)
      if (data.data.info) {
        if (data.data.info.coupon.is_applicable_store) {
          this.getStore();
        }
      }
    } else {
      app.tips(data.msg)
    }
  },
  async getStore() {
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.new-coupon.frontend.controllers.coupon.get-applicable-store"),
      data: {
        id: this.data.info_arr.coupon.id
      }
    })
    console.log(data)
    if (data.result) {
      this.setData({
        store_list: data.data.list.data,
        'storeCoupon.total_page': data.data.list.last_page,
        'storeCoupon.total': data.data.list.total
      })
    } else {
      app.tips(data.msg);
    }
  },
  async getMoreData() {
    if (!this.data.isLoadMore) return;
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.storeCoupon.page >= this.data.storeCoupon.total_page) {
      return;
    } else {
      let json = {
        page: this.data.storeCoupon.page,
        id: this.data.info_arr.coupon.id
      }
      let {
        data
      } = await app._postNetWork({
        url: app.getNetAddresss("plugin.new-coupon.frontend.controllers.coupon.get-applicable-store"),
        data: json
      })
      this.data.isLoadMore = true;
      if (data.result) {
        this.setData({
          store_list: this.data.store_list.concat(data.data.list.data)
        })
      } else {
        app.tips(data.msg);
        this.setData({
          'storeCoupon.page': this.data.storeCoupon.page - 1,
          isLoadMore: false
        })
      }
    }

  },
  goBuy(e) {
    let item = this.data.datainfo;
    this.couponMapFun(item);
  },
  couponMapFun(item) {
    const couponMap = [
      [
        () => item.use_type == 0,
        () => {
          //0商城通用
          this.goHome();
        }
      ],
      [
        () => item.use_type == 1,
        () => {
          //1指定分类
          if (item.plugin_id == 32) {
            //门店商品优惠券
            wx.navigateTo({
              url: `/packageC/o2o/StoreSearch/StoreSearch?store_id=${item.storeids}&cid=${item.category_ids}`
            });
            return;
          }
          wx.navigateTo({
            url: `/packageB/member/category/catelist/catelist?id=${JSON.stringify(item.category_ids)}&fromHome=1`
          });
        }
      ],
      [
        () => item.use_type == 2 || item.use_type == 8,
        () => {
           //2指定商品
          if (item.plugin_id == 32) {
            //门店商品优惠券
            wx.navigateTo({
              url: `/packageC/o2o/StoreSearch/StoreSearch?store_id=${item.storeids}&goods_ids=${item.goods_ids.join(",")}`
            });
          } else {
            wx.navigateTo({
              url: `/packageB/member/category/search_v2/search_v2?coupon=${item.id}&fromHome=1`
            });
          }
        }
      ],
      [
        () => item.use_type === 4 && Array.isArray(item.storeids),
        () => {
          //4门店列表
          wx.navigateTo({
            url: '/packageC/o2o/o2oHome/o2oHome'
          });
        }
      ],
      [
        () => item.use_type === 5 && typeof item.storeids === "number",
        () => {
          //5单门店
          wx.navigateTo({
            url: `/packageC/o2o/o2oStore/o2oStore?store_id=${item.storeids}`
          });
        }
      ],
      [
        () => item.use_type === 6 && typeof item.hotel_ids === "number",
        () => {
          wx.navigateTo({
            url: `/packageC/hotel/HotelHome/HotelHome?id=${item.hotel_ids}`
          });
        }
      ],
      [
        () => item.use_type === 7 && Array.isArray(item.hotel_ids),
        () => {
          wx.navigateTo({
            url: '/packageC/hotel/HotelIndex/HotelIndex'
          });
        }
      ]
    ];
    const targetFn = couponMap.find(couItem =>  couItem[0]());
    if (targetFn && targetFn[0] && targetFn[0]()) {
        targetFn[1]();
    } else {
      this.goHome();
    }
  },
  goHome() {
    wx.reLaunch({
      url: '/packageG/index/index',
    });
  },
})